<template>
  <div class="body-wrapper">
    <div class="body-top">
      <p>
        <!-- 查询 -->
        <span class="select">
          <h4>码表状态:</h4>
          <a-select ref="select" v-model:value="searchconditions.selectValue" :options="options" style="width: 120px" @change="handleChange"> </a-select>
        </span>

        <span class="select">
          <h4>码表名称:</h4>
          <a-input v-model:value="searchconditions.inputValue" placeholder="请输入码表名称" />
        </span>
        <a-button @click="reset">重置</a-button>&nbsp;
        <a-button type="primary" @click="search">查询</a-button>
      </p>
      <p>
        <a-button :disabled="activeClass1" :class="{ activeClass: !activeClass1, issue: true }" @click="allIssue()">批量发布</a-button>&nbsp;
        <a-button :disabled="activeClass2" :class="{ activeClass: !activeClass2, pause: true }" @click="allpause()">批量停用</a-button>
        <a-button type="primary" @click="downloadFile">码表模板下载</a-button>&nbsp;
        <!-- 码表导入 -->
        <a-button type="primary" @click="handleClickCodeIn">码表导入</a-button>&nbsp;
        <!-- 码表导入弹出 -->
        <file-up :is-file-up="isFileUp" @close-file-up="handleCloseFileUp"></file-up>
        <!-- 新增码表弹窗 -->
        <a-button type="primary" @click="showModal(dataSource)">新增码表</a-button>
        <AddCodeDialog
          :data-list="datas"
          :new-data="newData"
          :code-dialog-name="codeDialogName"
          :dialog-statue="dialogStatue"
          :add-code-table="addCodeTable"
          @change-show="showAddCodeDialog"
          @edit-successed="handleEditSuccessed"
          @add-dislog-data="addDislogData"
        >
        </AddCodeDialog>
      </p>
    </div>
    <br />
    <!-- 表格 -->

    <div class="relative py-8">
      <a-table
        :data-source="dataSource"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: selectedRowKeys1, onChange: selectChangEtion }"
        :row-key="(record: any) => { return record.codesId }"
      >
        <!-- <a-table-column></a-table-column> -->
        <a-table-column key="codesId" title="码表编号">
          <template #default="{ column, record }">
            <template v-if="column.key === 'codesId'">
              <a @click="showSmallModal(record.configsId, record.codesId)">
                {{ record.codesId }}
              </a>
            </template>
          </template>
        </a-table-column>
        <!-- <small-table :visible-small-modal="visibleSmallModal"></small-table> -->

        <a-table-column key="codesName" data-index="codesName">
          <template #title><span>码表名称</span></template>
        </a-table-column>
        <a-table-column key="codesMsg" data-index="codesMsg">
          <template #title><span>码表说明</span></template>
        </a-table-column>
        <a-table-column key="codesStatus" data-index="码表状态">
          <template #title><span>码表状态</span></template>
          <template #default="{ record }">
            <span>
              <a-tag :color="Colors[record.codesStatus]">{{ Status[record.codesStatus] }}</a-tag>
            </span>
          </template>
        </a-table-column>
        <a-table-column
          key="modifyTime"
          data-index="modifyTime"
          :sorter="
            (a: DataItem, b: DataItem) => {
              return a.modifyTime > b.modifyTime ? 1 : -1;
            }
          "
        >
          <template #title><span>更新时间</span></template>
        </a-table-column>
        <a-table-column key="action" title="操作">
          <template #default="{ record }">
            <span>
              <template v-if="record.codesStatus == 2">
                <a-popconfirm title="请确认是否停用该码表？" ok-text="是" cancel-text="否" @confirm="confirm3(record.codesId)" @cancel="cancel">
                  <a-button class="operate" type="primary">停用</a-button></a-popconfirm
                >
              </template>
              <template v-else-if="record.codesStatus == 3">
                <a-popconfirm title="请确认是否发布该码表？" ok-text="是" cancel-text="否" @confirm="confirm2(record.codesId)" @cancel="cancel">
                  <a-button class="operate" type="primary">发布</a-button></a-popconfirm
                >
                <a-button class="operate" type="primary" @click="showEditModal(record)">编辑</a-button>
              </template>
              <template v-else-if="record.codesStatus != 3">
                <a-popconfirm title="请确认是否发布该码表？" ok-text="是" cancel-text="否" @confirm="confirm2(record.codesId)" @cancel="cancel">
                  <a-button class="operate" type="primary">发布</a-button>
                </a-popconfirm>
                <a-button class="operate" type="primary" @click="showEditModal(record)">编辑</a-button>

                <a-popconfirm v-if="dataSource.length" title="请确认是否删除该码表？" ok-text="是" cancel-text="否" @confirm="confirm1(record.codesId)" @cancel="cancel">
                  <a-button class="operate" type="primary">删除</a-button></a-popconfirm
                >
              </template>
            </span>
          </template>
        </a-table-column>
      </a-table>
    </div>
  </div>
  <!-- 码表编号弹窗组件 -->
  <small-table :visible-small-modal="visibleSmallModal" :table-small-modal="tableSmallModal" :small-modal-id="smallModalId" @change-show="handleChangeShowSmallModal"></small-table>
</template>
<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import { getList, searchList, modifyAllStatu, modifyStatu, delList } from '@/api/test/api';
  import { reactive, ref, onMounted } from 'vue';
  import type { Ref, UnwrapRef } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import AddCodeDialog from './component/AddCodeDialog.vue';
  import fileUp from '../component/fileUp.vue';
  import smallTable from '../component/smallTable.vue';
  import { Status, Colors } from '@/pages/enumType/enum';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { conditionsType, DataItem, SmallModal } from './type/types';
  // 码表状态下拉框数据
  const options = [
    { value: 1, label: '未发布' },
    { value: 2, label: '已发布' },
    { value: 3, label: '已停用' },
  ];

  //中间部分的头部
  const searchconditions: conditionsType = reactive({
    selectValue: '请选择',
    inputValue: '',
  });
  // const handleChange = (value: string) => {
  //   // console.log(`selected ${value}`);
  // };
  const reset = () => {
    searchconditions.selectValue = '请选择';
    searchconditions.inputValue = '';
  };
  //码表导出
  function downloadFile() {
    window.location.href = '/码表模板.docx';
  }
  //码表导入开始
  const headers = {
    authorization: 'authorization-text',
  };
  let isFileUp: Ref<boolean> = ref(false);
  const handleClickCodeIn = () => {
    isFileUp.value = true;
    console.log('打开了');
  };
  const handleCloseFileUp = (isShow: string) => {
    isFileUp.value = false;
  };
  //码表导入结束

  const dataSource: Ref<DataItem[]> = ref([]);
  // dataSource.value = [
  //   {
  //     codesId: 'MZB0002',
  //     codesName: 'dah晒还是a',
  //     codesMsg: 'd嗲的话',
  //     codesStatus: 2,
  //     codesModifyTime: '2022-03-21 08:20:45',
  //   },
  //   {
  //     codesId: 'MZB0003',
  //     codesName: '大大大',
  //     codesMsg: 'd嗲的话',
  //     codesStatus: 3,
  //     codesModifyTime: '2022-03-21 18:20:45',
  //   },
  //   {
  //     codesId: 'MZB0004',
  //     codesName: '佳佳大大',
  //     codesMsg: 'd嗲的dddddf话',
  //     codesStatus: 1,
  //     codesModifyTime: '2022-03-11 08:20:45',
  //   },
  // ];
  let newData = ref<string>('');
  onMounted(async () => {
    const resGetList = await getList({});
    dataSource.value = resGetList.data.codesInfoVoList;
    console.log(resGetList.data, '222');

    if (newData.value == '') {
      newData.value = String(
        dataSource.value.map((item: DataItem) => {
          return item.codesName;
        }),
      );
    }
  });
  //  接口查询
  const search = () => {
    let data: {
      codesStatus?: string;
      codesName?: string;
    };
    if (searchconditions.inputValue != '' && searchconditions.selectValue == '请选择') {
      data = {
        codesName: searchconditions?.inputValue,
      };
    } else if (searchconditions?.inputValue == '' && searchconditions?.selectValue == '请选择') {
      data = {};
    } else {
      data = {
        codesStatus: searchconditions?.selectValue,
        codesName: searchconditions?.inputValue,
      };
    }
    getList(data).then(function (res: any) {
      dataSource.value = res.data;
      console.log(res.data);
    });
    console.log(data, '---');
  };
  let selectedRowKeys1: Ref<string[]> = ref([]);
  const arrPause: Ref<string[]> = ref([]); //停用数组
  const arrIssue: Ref<string[]> = ref([]); //发布数组
  const selectChangEtion = (selectedRowKeys: string[], selectedRows: DataItem[]) => {
    selectedRowKeys1.value = selectedRowKeys;
    let pauseCount = 0;
    let IssueCount = 0;
    arrIssue.value = [];
    arrPause.value = [];
    activeClass1.value = true; //发布按钮变为禁用
    activeClass2.value = true; //停用按钮变为禁用
    // 1未发布 2 已发布 3 已停用
    // if (selectedRows.length >= 2) {
    selectedRows.forEach(item => {
      if (item.codesStatus != 2) {
        pauseCount += 1; //记下一个可以发布的
        arrIssue.value.push(item.codesId);
      } else {
        IssueCount += 1; // 记下一个可以停用的
        arrPause.value.push(item.codesId);
      }
    });
    if (pauseCount >= 1) {
      activeClass1.value = false; //发布按钮变为可用
    }
    if (IssueCount >= 1) {
      activeClass2.value = false; //停用按钮变为可用
    }
    // }
    console.log(arrIssue.value, '要发布');
    console.log(arrPause.value, '要停用');
    selectedRowKeys = [];
  };
  // const visible = ref<boolean>(false);
  const addCodeTable = ref<boolean>(false);
  let codeDialogName = ref<boolean>(false);
  const activeClass1 = ref(true);
  const activeClass2 = ref(true);

  //批量发布和批量停用
  const allIssue = (num: number, status: number) => {
    //发布  num为3， stat
    //停用
    // console.log(arrIssue.value, '发布');
    selectedRowKeys1.value = [];
    activeClass1.value = true; //发布按钮变为禁用
    activeClass2.value = true; //停用按钮变为禁用
    // 1：未发布，2：已发布，3：已停用
    let data = {
      codesId: arrIssue.value,
      codesStatus: '3',
    };
    // modifyAllStatu(data).then(res => {
    if (arrIssue.value.length >= 2) {
      arrIssue.value.forEach((i: string) => {
        dataSource.value.forEach(item => {
          if (i == item.codesId) {
            item.codesStatus = 2;
            console.log('sss', item.codesStatus);
          }
        });
      });
    }
    // });
  };

  //批量停用
  const allpause = () => {
    let data = {
      codesId: arrPause.value,
      codesStatus: '2',
    };
    // console.log(arr.value)
    // modifyAllStatu(data).then(res => {
    arrPause.value.forEach((i: string) => {
      dataSource.value.forEach(item => {
        if (i == item.codesId) {
          item.codesStatus = 3;
        }
      });
    });

    // });
  };

  //删除
  const confirm1 = (codesId: string) => {
    delList({ codesId }).then(res => {
      dataSource.value = dataSource.value.filter(item => item.codesId !== codesId);
      message.success('删除成功！');
    });
    selectedRowKeys1.value = [];
  };

  //发布
  const confirm2 = (codesId: string) => {
    modifyStatu({ codesId }).then(function (res: any) {
      dataSource.value.filter(item => {
        if (item.codesId == codesId) {
          item.codesStatus = 2;
        }
      });
      message.success('发布成功！');
    });
    selectedRowKeys1.value = [];
  };

  //停用
  const confirm3 = (codesId: string) => {
    modifyStatu({ codesId }).then(function (res: any) {
      dataSource.value.filter(item => {
        if (item.codesId == codesId) {
          item.codesStatus = 3;
        }
      });
      message.success('停用成功！');
    });
    selectedRowKeys1.value = [];
  };
  const cancel = (e: MouseEvent) => {
    message.error('操作失败！');
  };

  const dialogStatue = ref<string>('');
  // 展开新增弹窗
  const showModal = (dataSource: DataItem[]) => {
    // addCodeTable 是控制弹窗展示的变量
    addCodeTable.value = true;
    dialogStatue.value = 'add';
  };
  // 展示新增数据
  const addDislogData = (data: { codesId: string }) => {
    data.codesId = 'MZB000';
  };
  // 展开编辑弹窗
  let datas = ref<Object>('');
  const showEditModal = (record: string) => {
    addCodeTable.value = true;
    dialogStatue.value = 'edit';
    datas.value = record;
  };
  const handleEditSuccessed = (data: { codesId: string; codesName: string; codesMsg: string }) => {
    dataSource.value.forEach(item => {
      if (item.codesId == data.codesId) {
        item.codesName = data.codesName;
        item.codesMsg = data.codesMsg;
      }
    });
  };
  // ---------------------------------
  // 新增码表弹窗中的表格
  const showAddCodeDialog = (show: string) => {
    // 子组件向外触发父组件事件“关闭”新增码表弹窗
    if (show === 'false') {
      addCodeTable.value = false;
    } else {
      addCodeTable.value = true;
    }
  };

  //码表编号弹窗
  const visibleSmallModal = ref(false);
  let smallModalId = ref<string>('');
  const tableSmallModal: Ref<SmallModal[]> = ref([]);
  const showSmallModal = (configsId: number, codesNo: string) => {
    visibleSmallModal.value = true;
    // 查询人员性别码表
    smallModalId.value = codesNo;
    console.log(visibleSmallModal);
    const ressearchList = searchList({ codesNo });
    console.log(ressearchList);
    // tableSmallModal.value = ressearchList.data;
  };
  const handleChangeShowSmallModal = () => {
    visibleSmallModal.value = false;
  };

  // 分页
  let pagination = {
    defaultPageSize: 20,
    showTotal: (total: number) => `共 ${total} 条`,
    showSizeChanger: true,
    showQuickJumper: true,
    position: ['bottomCenter'],
    pageSizeOptions: ['5', '10', '15', '20'],
    onShowSizeChange: (current: number, pageSize: number) => pageSize,
  };
</script>
<style lang="less" scoped>
  .body-wrapper {
    margin-top: 10px;
    width: 100%;

    .body-top {
      display: flex;
      justify-content: space-around;
      width: 90%;
      flex-wrap: wrap;

      p {
        display: flex;
        justify-content: center;
        width: 100%;
        height: 20px;
      }

      p:nth-child(2) {
        .issue {
          // margin: 0 10px 0 0;
        }

        .pause {
          margin: 0 50% 0 0;
        }
      }
      // 弹窗

      .select {
        display: flex;
        width: 200px;
        height: 40px;
        line-height: 40px;

        .ant-select {
          margin-left: 5px;
        }

        .ant-input {
          margin-left: 5px;
          width: 120px;
          height: 32px;
        }
      }

      .ant-btn-primary {
        border: none;
        background-color: rgb(49, 149, 216) !important;
      }

      .activeClass {
        color: aliceblue;
        background-color: #3195d8 !important;
      }

      .editable-cell:hover .editable-cell-icon {
        display: inline-block;
      }
    }

    .relative {
      /deep/ .ant-table {
        min-height: 68vh;
      }
    }

    .operate {
      margin: 2px;
      background-color: rgb(49, 149, 216) !important;
    }
  }

  .ant-btn {
    border-radius: 5px;
  }
</style>
